package grid;

import java.util.Arrays;
import java.util.Iterator;

public final class Grid implements Iterable<GridPoint>{
	
	private final GridPoint[] gridPoints;
	public final Grid father;
	protected Grid(GridPoint[] gridPoints, Grid father){
		this.gridPoints = gridPoints;
		this.father = father;
	}
	
	public int size(){
		return gridPoints.length;
	}
	
	public GridPoint get(int i) {
		return gridPoints[i];
	}
	
	/**
	 * generates a new Builder that is filled with entrys from this grid.
	 * @return
	 */
	public GridBuilder getBuilder(){
		if (father == null) {
			return new GridBuilder(gridPoints, this);
		}
		return new GridBuilder(gridPoints, father);
	}
	
	
	public double[][] toDoubleArray(){
		double[][] xs = new  double[gridPoints.length][2];
		for (int i = 0; i < xs.length; i++) {
			xs[i][0] = gridPoints[i].x;
			xs[i][1] = gridPoints[i].y;
		}
		return xs;
	}
	

	@Override
	public Iterator<GridPoint> iterator() {
		return new Iterator<GridPoint>() {
			int counter = 0;
			@Override
			public void remove() {
				throw new UnsupportedOperationException("Grid is immutable");
			}
			
			@Override
			public GridPoint next() {
				return gridPoints[counter++];
			}
			
			@Override
			public boolean hasNext() {
				return counter<size();
			}
		};
	}

	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Grid [gridPoints=");
		builder.append(Arrays.toString(gridPoints));
		builder.append(", father=");
		builder.append(father);
		builder.append("]");
		return builder.toString();
	}


	
	
	
	

}
